﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using Example;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using YJTMedicalAideManage.Cores;
using YJTMedicalAideManage.Cores.ApiModel;
using YJTMedicalAideManage.Cores.Attributes;
using YJTMedicalAideManage.Cores.Events;
using YJTMedicalAideManage.Cores.Globals;
using YJTMedicalAideManage.Cores.Helper;
using YJTMedicalAideManage.Cores.Models;
using YJTMedicalAideManage.Cores.Servers;
using YJTMedicalAideManage.Model;

namespace YJTMedicalAideManage.ViewModels
{
    public class LoginViewModel : InheritBase
    {

        private string _username;
        private string _password;
        private string _descriptionUsername;
        private string _descriptionPassword;
        private bool isSavePwd;
        public bool IsSavePwd
        {
            get => isSavePwd;
            set
            {
                isSavePwd = value;
                RaisePropertyChanged();
            }
        }
        public string DescriptionUsername
        {
            get => _descriptionUsername;
            set
            {
                _descriptionUsername = value;
                RaisePropertyChanged();
            }
        }
        public string DescriptionPassword
        {
            get => _descriptionPassword;
            set
            {
                _descriptionPassword = value;
                RaisePropertyChanged();
            }
        }
        public string Username
        {
            get => _username;
            set
            {
                _username = value;
                RaisePropertyChanged();
                DescriptionUsername = "";
            }
        }

        public string Password
        {
            get => _password;
            set
            {
                _password = value;
                RaisePropertyChanged();
                DescriptionPassword = "";
            }
        }
        private Visibility showpwd;

        public Visibility Showpwd
        {
            get => showpwd;
            set
            {
                showpwd = value;
                RaisePropertyChanged();
            }
        }
        private Visibility closepwd;

        public Visibility Closepwd
        {
            get => closepwd;
            set
            {
                closepwd = value;
                RaisePropertyChanged();
            }
        }
        public event Action LoginSuccess;
        private readonly ApiService _apiService;
        private ModeSwitching modeSwitching;
        public LoginViewModel()
        {
            _user = new user();
            DescriptionUsername = "用户名";
            DescriptionPassword = "密码";
            _apiService = new ApiService();
            modeSwitching = new ModeSwitching();
            LoginCommand = new DelegateCommand(OnLogin);
            ShowPwdCommand = new DelegateCommand(ShowPwd);
            Init();
        }

        private user _user;
        public DelegateCommand LoginCommand { get; private set; }
        public DelegateCommand ShowPwdCommand { get; private set; }

        #region 方法
        private async void OnLogin()
        {
            await LoadingMaskInterceptor.Instance().InterceptAsync(async () => await OnLoginSuccess());
        }
        private async void Init()
        {

            PwdStringEvent.Instance.Subscribe(InitPwd);
            //GlobalApp.Instance.LoadDataFromJson("./Jsons/AreaInfo.json");
            Closepwd = Visibility.Visible;
            Showpwd = Visibility.Collapsed;
            var userDto = IniHelper.Instance.ReadFromIni<user>("UserInfo", @"./Ini/UserInfo.ini");
            if (userDto.isSavePwd == "1")
            {
                IsSavePwd = true;
                Password = userDto.pwd;
                Username = userDto.username;

                PwdStringEvent.Instance.PushMessage($"设置密码{Password}");
            }
            var mode = IniHelper.Instance.DoesFileExist(@"./Ini/ModeInfo.ini");
            if (mode == false)
            {
                modeSwitching.BaseUrl = "https://dvp.lianjieit.net/his_dvp/";
                modeSwitching.ClinicId = "738CE51D1E231C1A";
                modeSwitching.RoleId = "443";
                modeSwitching.Scale = "0";
                IniHelper.Instance.SaveToIni(modeSwitching, "ModeSwitching", @"./Ini/ModeInfo.ini");
            }
            else
            {
                var modeDto = IniHelper.Instance.ReadFromIni<ModeSwitching>("ModeSwitching", @"./Ini/ModeInfo.ini");
                modeSwitching.BaseUrl = modeDto.BaseUrl;
                modeSwitching.ClinicId = modeDto.ClinicId;
                modeSwitching.RoleId = modeDto.RoleId;
                modeSwitching.Scale = modeDto.Scale;
            }
            GlobalApp.Instance.Role_Id = modeSwitching.RoleId;
            GlobalApp.Instance.Scale = modeSwitching.Scale;
            GlobalApp.Instance.BaseUrl = modeSwitching.BaseUrl;
            GlobalApp.Instance.ClinicId = modeSwitching.ClinicId;
            
        }
        private async Task InitConfig()
        {
            var Pdata = await _apiService.GetAllProvinceAsync();
            foreach (var item in Pdata.data)
            {
                GlobalApp.Instance.ProvinceList.Add(new adddress { provinceName = item.provinceName, provinceId = item.provinceId });
            }
            var Cdata = await _apiService.GetAllCityAsync("");
            foreach (var item in Cdata.data)
            {
                GlobalApp.Instance.CityList.Add(new adddress { cityName = item.cityName, cityId = item.cityId });
            }
            var Adata = await _apiService.GetAllAreaAsync("");
            foreach (var item in Adata.data)
            {
                GlobalApp.Instance.AreaList.Add(new adddress { areaName = item.areaName, areaId = item.areaId });
            }
        }
        private void ShowPwd()
        {
            if (Showpwd == Visibility.Collapsed)
            {
                Showpwd = Visibility.Visible;
                Closepwd = Visibility.Collapsed;
            }
            else
            {
                Showpwd = Visibility.Collapsed;
                Closepwd = Visibility.Visible;
            }
            PwdStringEvent.Instance.PushMessage("查看密码");
        }

        private void InitPwd(string pwd)
        {
            if (pwd != "查看密码")
            {
                Password = pwd;
            }
        }
        [ShowLoadingMask]
        private async Task OnLoginSuccess()
        {

            await Task.Run(async () =>
            {
                try
                {
                    Password = GlobalApp.Instance.RemoveChineseCharacters(Password);
                    if (string.IsNullOrEmpty(Password) && string.IsNullOrEmpty(Username))
                    {
                        MessgaeError("账号或密码不能为空！");
                        return;
                    }
                    var response = await _apiService.LoginAsync(Username, Password);
                    if (response != null)
                    {
                        if (response.status == "success")
                        {

                            var data = response.data as login;
                            if (data != null && !string.IsNullOrEmpty(data.info))
                            {
                                if (MessgaeInfo(data.info) == MessageBoxResult.Yes)
                                {
                                    var apiLoginSes = await _apiService.LoginSetAsync(Username, Password);

                                    if (apiLoginSes.status == "success")
                                    {
                                        GlobalApp.Instance.Manager_Id = apiLoginSes.data.manager_id;
                                        GlobalApp.Instance.Token = apiLoginSes.data.token;
                                        await InitConfig();
                                        Application.Current.Dispatcher.Invoke(() =>
                                        {
                                            LoginSuccess?.Invoke();

                                        });

                                    }
                                    return;
                                }
                                else
                                {
                                    return;
                                }
                            }
                            var apiLoginSet = await _apiService.LoginSetAsync(Username, Password);

                            if (apiLoginSet.status == "success")
                            {
                                GlobalApp.Instance.Manager_Id = apiLoginSet.data.manager_id;
                                GlobalApp.Instance.Token = apiLoginSet.data.token;
                                await InitConfig();
                                if (IsSavePwd)
                                {
                                    _user.pwd = Password;
                                    _user.isSavePwd = IsSavePwd == true ? "1" : "0";
                                    _user.username = Username;
                                }
                                IniHelper.Instance.SaveToIni(_user, "UserInfo", "./Ini/UserInfo.ini");
                                // 触发登录成功事件
                                Application.Current.Dispatcher.Invoke(() =>
                                {
                                    LoginSuccess?.Invoke();
                                });
                            }

                        }
                        else
                        {
                            MessgaeError(response.msg);
                            return;
                        }

                    }
                }
                catch (Exception ex)
                {
                    MessgaeError(ex.Message);
                }
            });
        }
        #endregion

    }
}
